package controller

import (
	"strconv"

	"system-admin/config/mysql"
	"system-admin/internal/app/web/service/alarm"
	"system-admin/internal/dal"
	"system-admin/internal/dao"
	"system-admin/internal/models"

	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type Alarm struct{}

// GetAlarmReceiveStatus 获取告警接收状态
func (Alarm) GetAlarmReceiveStatus(c *gin.Context) {
	status := alarm.GetAlarmReceiveStatus(c.GetString("user_id"))
	response.JSON(c, map[string]interface{}{
		"status": status,
	}, nil)
}

// SetAlarmReceiveStatus 获取告警接收状态
func (Alarm) SetAlarmReceiveStatus(c *gin.Context) {
	var params struct {
		Status int `json:"status"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	err := alarm.SetAlarmReceiveStatus(c.GetString("user_id"), params.Status)
	response.JSON(c, nil, err)
}

// GetAlarmTypes 获取告警类型
func (Alarm) GetAlarmTypes(c *gin.Context) {
	res := alarm.GetAlarmTypes()
	response.JSON(c, res, nil)
}

// GetNotifyTypes 获取通知方式
func (Alarm) GetNotifyTypes(c *gin.Context) {
	res := alarm.GetNotifyTypes()
	response.JSON(c, res, nil)
}

// 通知规则列表
func (Alarm) NotifyRuleList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	limit, _ := strconv.Atoi(c.Query("limit"))
	res, total, err := alarm.NotifyRuleList(
		c.GetString("merchant_id"),
		page,
		limit,
	)
	if err != nil {
		response.JSON(c, map[string]interface{}{
			"list":  []string{},
			"total": 0,
		}, err)
	} else {
		response.JSON(c, map[string]interface{}{
			"list":  res,
			"total": total,
		}, nil)
	}
}

// 新增通知规则
func (Alarm) AddNotifyRule(c *gin.Context) {
	var params struct {
		Name         string `json:"name"`
		RobotIDs     string `json:"robot_ids"`
		AlarmTypes   string `json:"alarm_types"`
		ReceiveUsers string `json:"receive_users"`
		NotifyTypes  string `json:"notify_types"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	createdID, err := alarm.AddNotifyRule(
		params.Name,
		c.GetString("merchant_id"),
		params.RobotIDs,
		params.AlarmTypes,
		params.ReceiveUsers,
		params.NotifyTypes,
	)
	if err != nil {
		response.JSON(c, nil, err)
	} else {
		response.JSON(c, map[string]interface{}{
			"id": createdID,
		}, nil)
	}
}

// 编辑通知规则
func (Alarm) EditNotifyRule(c *gin.Context) {
	var params struct {
		ID           string `json:"id"`
		Name         string `json:"name"`
		RobotIDs     string `json:"robot_ids"`
		AlarmTypes   string `json:"alarm_types"`
		ReceiveUsers string `json:"receive_users"`
		NotifyTypes  string `json:"notify_types"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	err := alarm.EditNotifyRule(
		params.ID,
		params.Name,
		c.GetString("merchant_id"),
		params.RobotIDs,
		params.AlarmTypes,
		params.ReceiveUsers,
		params.NotifyTypes,
	)
	response.JSON(c, nil, err)
}

// 删除通知规则
func (Alarm) DeleteNotifyRule(c *gin.Context) {
	var params struct {
		ID string `json:"id"`
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	err := alarm.DeleteNotifyRule(params.ID, c.GetString("merchant_id"))
	response.JSON(c, nil, err)
}

// 告警通知记录
func (Alarm) AlarmNotifyRecords(c *gin.Context) {
	notRepeated, _ := strconv.Atoi(c.Query("not_repeated"))
	startTime, _ := strconv.Atoi(c.Query("start_time"))
	endTime, _ := strconv.Atoi(c.Query("end_time"))
	page, _ := strconv.Atoi(c.Query("page"))
	limit, _ := strconv.Atoi(c.Query("limit"))
	res, total, err := alarm.NotifyRecords(
		c.Request.Context(),
		c.GetString("merchant_path")+">"+c.GetString("merchant_id"),
		c.Query("alarm_type"),
		c.Query("robot_id"),
		c.Query("receive_user"),
		int64(startTime),
		int64(endTime),
		c.Query("province_id"), c.Query("city_id"), c.Query("district_id"), c.Query("location_id"),
		page, limit,
		notRepeated > 0,
	)
	if err != nil {
		response.JSON(c, map[string]interface{}{
			"list":  []string{},
			"total": 0,
		}, err)
	} else {
		response.JSON(c, map[string]interface{}{
			"list":  res,
			"total": total,
		}, nil)
	}
}

// NotifyDetail 告警通知详情
func (Alarm) NotifyDetail(c *gin.Context) {
	recordID := c.Query("id")
	var record models.AlarmNotifyRecord
	mysql.NewDB().Model(&models.AlarmNotifyRecord{}).Where("id = ?", recordID).Take(&record)
	c.Request.Header.Set("content-type", "text/html")
	c.Writer.Write([]byte(`
		<html>
			<head>
				<meta name="viewport" content="width=device-width, initial-scale=1">
				<title>告警详情</title>
			</head>
			<body>
				<h4>告警ID：` + record.ID + `</h4>
				<h4>告警说明：` + record.Detail + `</h4>
			</body>
		</html>
	`))
}

// UserOption 告警通知的用户选项
// 包含所有的子商户用户
func (Alarm) UserOptions(c *gin.Context) {
	userOptions := []UserOptionType{}
	list, _ := dao.User{}.ListByUserMerchantPath(c.Request.Context(), dal.Q, c.GetString("user_merchant_path"))
	for _, record := range list {
		userOptions = append(userOptions, UserOptionType{
			ID:       record.ID,
			Username: record.Username,
		})
	}
	response.JSON(c, gin.H{
		"list": userOptions,
	}, nil)
}
